<?php
namespace collar;


use app\commons\model\Member;
use GuzzleHttp\Client;
use think\Exception;
use think\facade\Env;

class CollarBag
{

    /**
     * 同步用户信息，并获取用户领袋次数
     * @param $userId
     * @param $macId
     * @return mixed
     * @throws Exception
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function syncUser($userId,$macId){
        //接收参数
        $client = new Client();
        //获取用户信息
        $User = Member::where(['id'=>$userId])->field(['pt_openid','avatar','nickname','city','province','country'])->find();
        //请求参数
        $params = [
            'user' => [
                'id' => $User['pt_openid'], //自己生成的唯一凭据
                'avatar' => $User['avatar'],
                'original' => [
                    'openid' => $User['pt_openid'],
                    'nickname' => $User['nickname'],
                    'sex' => 0,
                    'language' => '',
                    'city' => $User['city'],
                    'province' => $User['province'],
                    'country' => $User['country'],
                    'headimgurl' => $User['avatar']
                ]]
        ];
        $res = $client->request('POST',Env::get('BAG_GET_TASK_NUM_URL').$macId,['json' => $params,'headers'=>['content-type'=>'application/json']]);
        if($res->getStatusCode() != 200){
            throw new Exception('同步用户信息失败！');
        }
        $data = $res->getBody()->getContents();
        $data = json_decode($data,true);
        return $data;
    }

    /**
     * 出袋
     * @param $userId
     * @param $macId
     * @return bool
     * @throws Exception
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function receive($userId, $macId){
        $client = new Client();
        $user = Member::where(['id'=>$userId])->field(['pt_openid'])->find();
        $params = [
            'user_id' => $user['pt_openid'],
            'mac_id' => $macId,
            'appid' => Env::get('BAG_APPID'),
        ];
        $params['sign'] = self::sign($params);
        $res = $client->request('POST',Env::get('BAG_OUT_BAG_URL'),['form_params' => $params]);
        $data = $res->getBody()->getContents();
        $data = json_decode($data,true);
        if($res->getStatusCode() != 200 || $data['code'] != 200){
            //出袋失败
            throw new Exception($data['msg'] ?? '出袋失败！');
        }
        return true;
    }


    /**
     * 签名
     * @param $params
     * @return string
     */
    public static function sign($params){
        // 对数组的值按key排序
        ksort($params);
        // 生成url的形式
        $params = http_build_query($params);
        $str_params = $params . '&key=' . Env::get('BAG_KEY');
        // 生成sign
        return strtoupper(md5($str_params));
    }
}